package com.jimster.plugins.gadgets.grid
{
	import flash.display.MovieClip;
	import flash.utils.getDefinitionByName;
	
	public class TileDuplicator extends MovieClip
	{
		/*
		Variables
		*/
		private var objParent:*;
		private var objTile:*;
		private var Tile:Class;
		private var mcTileContainer:MovieClip;
		private var numTotalTiles:Number;
		private var numPadding:Number=0;
		private var arrGridChilds:Array;
		
		/*
		Constructor
		*/
		public function TileDuplicator()
		{
			super();
		}
		
		/*
		Public methods
		*/
		public function initialize( $reference:*, $linkage:String ):void
		{
			this.Tile = Class( getDefinitionByName( $linkage )  );
			this.objParent = $reference;
			this.objTile = new Tile();
			this.createTiles();
		}
		
		public function updateGrid():void
		{
			this.removeChild( this.mcTileContainer );
			this.mcTileContainer = null;
			this.arrGridChilds = null;
			
			this.createTiles();
		}
		/*
		Private methods
		*/
		private function createTiles():void
		{
			this.mcTileContainer = new MovieClip();
			this.addChild( this.mcTileContainer );
			this.arrGridChilds = new Array();
			
			var _parentWidth:Number = Math.ceil( this.objParent.width );
			var _parentHeight:Number = Math.ceil( this.objParent.height );
			
			var _numRows:Number = Math.ceil( _parentWidth / this.objTile.width );
			var _numColumns:Number = Math.ceil( _parentHeight / this.objTile.height );
			
			this.numTotalTiles = _numRows * _numColumns;
			
			for( var i:uint = 0; i < this.numTotalTiles; i++ )
			{
				this.objTile = new Tile();
				this.objTile.x = ( this.objTile.width + this.numPadding ) * ( i % _numRows );
				this.objTile.y = ( this.objTile.height + this.numPadding ) * Math.floor( i / _numRows );
				
				this.mcTileContainer.addChild( this.objTile );
				this.arrGridChilds.push( this.objTile );
			}
		}
		/*
		Event handlers
		*/
		
		/*
		Accesors & setters
		*/
		public function get gridChildren():Array
		{
			return this.arrGridChilds;
		}
		
		public function set gridChildren( $value:Array ):void
		{
			this.arrGridChilds = $value;
		}
		
		public function get padding():Number
		{
			return this.numPadding;
		}
		
		public function set padding( $value:Number ):void
		{
			this.numPadding = $value;
		}
	}
}